<template>
  <div>
    <!-- 配置路由： /login -->
    <!-- 标题栏 -->
    <mt-header title="登录">
      <mt-button icon="back" slot="left"></mt-button>
      <router-link to="/register" slot="right">新用户</router-link>
    </mt-header>
    <!-- 表单 -->
    <mt-field
      v-model="name"
      type="text"
      label="用户名"
      placeholder="请输入用户名"
      :state="nameState"
      @blur.native.capture="checkName"
    ></mt-field>
    <mt-field
      v-model="pwd"
      type="password"
      label="密码"
      placeholder="请输入密码"
      :state="pwdState"
      @blur.native.capture="checkPwd"
    ></mt-field>
    <!-- 按钮 -->
    <mt-button type="primary" size="large" @click="login">安全登录</mt-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "",
      nameState: "",
      pwd: "",
      pwdState: "",
    };
  },
  methods: {
    // 验证密码
    checkPwd() {
      let reg = /^\d{6}$/;
      if (reg.test(this.pwd)) {
        this.pwdState = "success";
        return true;
      } else {
        this.pwdState = "error";
        return false;
      }
    },

    // 用户名输入框焦点失去后执行
    checkName() {
      // 验证账号
      let reg = /^\w{3,15}$/;
      if (reg.test(this.name)) {
        // 返回true，表示验证成功
        this.nameState = "success";
        return true;
      } else {
        this.nameState = "error";
        return false;
      }
    },
    login() {
      // 依次验证 name pwd
      if (this.checkName() && this.checkPwd()) {
        // 都验证通过之后 执行登录业务
        console.log(`${this.name}, ${this.pwd}`);
        
        let param = `username=${this.name}&password=${this.pwd}`
        this.axios.post('/login', param).then(res=>{
          console.log('登录结果:', res)
          if(res.data.code==200){ // 注册成功
            // 登录成功后  修改vuex中state里的登录状态，保存用户名
            // 通知vuex  执行mutations中的updateLoginState方法，更新state
            this.$store.commit("updateLoginState",this.name)
            
            this.$router.push('/')
            this.$toast('登录成功')
          }else{ // 注册失败
            this.$messagebox({
              title: '注意',
              message: '账号密码不正确'
            })
          }
        })
      }
    },
  },
};
</script>